package com.demo.project_template.config.swagger;

import com.demo.project_template.exception.ErrorCodeExceptionEnum;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
@Data
@ConfigurationProperties(prefix = "swagger-config")
public class SwaggerConfig {

    private String title;

    private String description;

    private String author;

    private String url;

    private String email;

    @Bean
    public Docket customDocket() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        Arrays.stream(ErrorCodeExceptionEnum.values()).forEach(resultCode -> {
            responseMessageList.add(
                    new ResponseMessageBuilder().code(resultCode.getCode()).message(resultCode.getMsg()).build());
        });

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.project_template.controller"))//扫描的包路径
                .build()
                .globalResponseMessage(RequestMethod.GET,responseMessageList)
                .globalResponseMessage(RequestMethod.POST,responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE,responseMessageList);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .description(description)
                .title(title)
                .version("1.0.0")
                .contact(new Contact(author, url, email))
                .build();
    }

}